﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;
using ShareMarking.Systems.Service;

namespace ShareMarking.Systems.Services
{
    public class FileManager
    {
        /// <summary>
        /// 创建文件夹
        /// </summary>
        private void CreateDir(string foldname,string time,string timedate)
        {
            string avatarDir = string.Format("/Upload/{0}/{1}/{2}/",foldname,time,timedate);

            if (!Directory.Exists(HttpContext.Current.Server.MapPath(avatarDir)))
                Directory.CreateDirectory(HttpContext.Current.Server.MapPath(avatarDir));
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="foldname">文件夹名</param>
        /// <param name="filetype">文件后缀名</param>
        /// <param name="file">文件</param>
        /// <param name="userid">用户ID</param>
        /// <param name="fileurl">返回的文件地址</param>
        /// <returns></returns>
        public bool SaveFile(string foldname, HttpPostedFile file, out string physicsAvatarPath)
        {
            var now = DateTime.Now;
            string time = now.ToString("yyyyMM");
            string timedate = now.ToString("dd");
            CreateDir(foldname, time, timedate);

            string fileExt = Utils.GetFileExt(file.FileName); //文件扩展名，不含“.”

            var timems = now.ToString("yyyyMMddHHmmssffff");
            physicsAvatarPath = string.Format("/Upload/{0}/{1}/{2}/{3}.{4}", foldname, time, timedate, timems, fileExt);

            string fileurl = Utils.GetMapPath(physicsAvatarPath);

            file.SaveAs(fileurl);
            return true;
        }
    }
}
